<?php

namespace App\Models;

use App\Models\Customer\Follow;
use App\Models\Order\Order;
use Illuminate\Database\Eloquent\Model;

class Video extends Model
{
    protected $table = 'video_files';

    protected $fillable = [
        'title',
        'image',
        'video',
        'category_id',
        'teacher_id',
        'introduction',
        'price',
        'details',
        'state',
        'author_id',
        'status'
    ];

    protected $appends = [
        'price'
    ];

    protected $casts = [
        'state'  => 'boolean',
    ];

    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id', 'id');
    }

    public function teacher()
    {
        return $this->belongsTo(Teacher::class, 'teacher_id', 'id');
    }

    public function imaging()
    {
        return $this->hasOne(FileTransaction::class, 'id', 'image');
    }

    public function videoing()
    {
        return $this->hasOne(FileTransaction::class, 'id', 'video');
    }

    public function setPriceAttribute($value)
    {
        $this->attributes['price'] = intval($value * 100);
    }

    public function getPriceAttribute($value)
    {
        return empty($this->attributes['price']) ? 0 : round($this->attributes['price'] / 100, 2);
    }

    public function follow()
    {
        $user = auth('customer')->user();
        return $this->hasOne(Follow::class, 'video_id', 'id')->where('author_id', $user->id ?? 0);
    }

    public function sumOrder()
    {
        return Order::countQty($this);
    }
}
